import "package:craze/common/index.dart";
import "package:craze/models/index.dart";
import "package:craze/services/index.dart";
import "package:craze/stores/index.dart";
import "package:flutter/material.dart";
import "package:flutter_screenutil/flutter_screenutil.dart";
import "package:go_router/go_router.dart";
import "package:google_fonts/google_fonts.dart";
import "package:flutter_mobx/flutter_mobx.dart";

class MyProfileView extends StatefulWidget {
  const MyProfileView({super.key});

  @override
  State<MyProfileView> createState() => _MyProfileViewState();
}

class _MyProfileViewState extends State<MyProfileView> {
  // 获取auth_store实例
  final AuthStore _authStore = getIt<AuthStore>();
  final ShareStore _shareStore = getIt<ShareStore>();
  final ChatService _chatService = getIt<ChatService>();
  // 添加CollectionStore实例
  final CollectionStore _collectionStore = getIt<CollectionStore>();

  // 添加错误状态
  String? _errorMessage;
  bool _isLoading = false;
  int _chatCount = 0; // 聊天数量

  // 记录收藏状态
  final Map<String, bool> _collectStatus = {};

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    if (!mounted) return;
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      if (_authStore.isLoggedIn) {
        await _shareStore.loadShares();
        await _collectionStore.loadUserCollections();
        _initCollectStatus();

        // 获取聊天数量
        if (_authStore.currentUser != null) {
          final userChats = getIt<ChatService>().getUserChats(
            _authStore.currentUser!.id,
          );
          _chatCount = userChats.length;
        }

        // 重新获取最新用户数据
        final user = getIt<UserService>().getUserById(
          _authStore.currentUser!.id,
        );
        if (user != null) {
          _authStore.currentUser = user;
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = "Failed to load data: ${e.toString()}";
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 初始化收藏状态
  void _initCollectStatus() {
    if (_authStore.currentUser != null) {
      final userShares = _shareStore.userShares;
      for (var share in userShares) {
        _collectStatus[share.id] = _collectionStore.isShareInCollection(
          share.id,
        );
      }
    }
  }

  // 切换收藏状态
  Future<void> _toggleCollect(String shareId) async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) return;

    setState(() {
      // 先在UI上立即更新状态，提供更好的用户体验
      _collectStatus[shareId] = !(_collectStatus[shareId] ?? false);
    });

    try {
      // 使用CollectionStore的toggleShareCollection方法
      await _collectionStore.toggleShareCollection(shareId);

      // 更新分享状态 - 通过标记重新加载来实现
      await _shareStore.loadShares(); // 重新加载分享数据以更新状态
    } catch (e) {
      // 如果操作失败，恢复原状态
      setState(() {
        _collectStatus[shareId] = !(_collectStatus[shareId] ?? false);
      });

      // 显示错误提示
      if (mounted) {
        MyToast.showError(
          context,
          "Failed to update collection: ${e.toString()}",
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          top: false,
          child:
              _errorMessage != null
                  ? _buildErrorView()
                  : Observer(
                    builder: (_) {
                      try {
                        // 根据登录状态显示不同内容
                        if (_authStore.isLoggedIn) {
                          return _buildLoggedInView();
                        } else {
                          return _buildNotLoggedInView();
                        }
                      } catch (e) {
                        // 处理在构建过程中发生的错误
                        return _buildErrorView(message: e.toString());
                      }
                    },
                  ),
        ),
      ),
    );
  }

  // 错误视图
  Widget _buildErrorView({String? message}) {
    final errorMsg = message ?? _errorMessage ?? "An unknown error occurred";

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, color: Colors.white, size: 60.sp),
          SizedBox(height: 20.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            child: Text(
              errorMsg,
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 16.sp),
            ),
          ),
          SizedBox(height: 20.h),
          ElevatedButton(onPressed: _loadUserData, child: Text("Retry")),
        ],
      ),
    );
  }

  // 已登录状态的视图
  Widget _buildLoggedInView() {
    // 安全地获取用户数据和分享
    final user = _authStore.currentUser;
    if (user == null) {
      return _buildNotLoggedInView(); // 回退到未登录视图
    }

    final userPosts = _shareStore.userShares;

    return SingleChildScrollView(
      child: Column(
        children: [
          Stack(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Image.asset(MyImages.mineCard, fit: BoxFit.fill),
              ),

              // 顶部标题等
              Positioned(
                top: 56.h,
                left: 20.w,
                child: Text(
                  'Personal',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                    height: 1.36,
                  ),
                ),
              ),

              Positioned(
                top: 56.h,
                right: 20.w,
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.collect);
                      },
                      child: Icon(
                        MyIcons.iconCollect,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                    SizedBox(width: 20.w),
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.setup);
                      },
                      child: Icon(
                        MyIcons.iconSetup,
                        color: Colors.white,
                        size: 26.sp,
                      ),
                    ),
                  ],
                ),
              ),

              // 用户信息
              Positioned(
                top: 190.h,
                left: 44.w,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    // 头像
                    Container(
                      width: 60.w,
                      height: 60.w,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(
                            user.avatar.isNotEmpty
                                ? user.avatar
                                : MyImages.touxiang1,
                          ),
                          fit: BoxFit.cover,
                        ),
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2.w),
                      ),
                    ),
                    SizedBox(width: 10.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 用户名
                        Text(
                          user.name,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18.sp,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        SizedBox(height: 9.h),
                        // 用户签名
                        Container(
                          constraints: BoxConstraints(maxWidth: 179.w),
                          child: Text(
                            user.description.isEmpty
                                ? 'Introduce yourself to everyone!'
                                : user.description,
                            style: TextStyle(
                              color: Colors.white.withAlpha(153),
                              fontSize: 14.sp,
                              fontFamily: GoogleFonts.baloo2().fontFamily,
                              fontWeight: FontWeight.w400,
                              height: 1.07,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(width: 40.w),

                    // 编辑信息
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.edit);
                      },
                      child: Container(
                        width: 40.w,
                        height: 40.w,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          MyIcons.iconEdit2,
                          color: MyColors.blue,
                          size: 22.sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 用户数据
              Positioned(
                top: 300.h,
                left: 44.w,
                right: 44.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 关注
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.follow);
                      },
                      child: _buildUserDataItem(
                        user.followingIds.length.toString(),
                        'Follow',
                      ),
                    ),
                    // 粉丝
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.fans);
                      },
                      child: _buildUserDataItem(
                        user.followerIds.length.toString(),
                        'Fan',
                      ),
                    ),
                    // 聊天
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).push(AppRouter.message);
                      },
                      child: _buildUserDataItem(_chatCount.toString(), 'Chat'),
                    ),
                  ],
                ),
              ),
            ],
          ),

          // 这里可以添加更多内容
          SizedBox(height: 20.h),

          // 我的作品
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Release',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 22.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                  fontWeight: FontWeight.w400,
                  height: 1.36,
                ),
              ),
            ),
          ),

          // 我的作品列表
          SizedBox(height: 16.h),

          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child:
                _isLoading
                    ? _buildLoadingView()
                    : userPosts.isEmpty
                    ? _buildEmptyView()
                    : Column(
                      children:
                          userPosts.map((post) {
                            return Padding(
                              padding: EdgeInsets.only(bottom: 20.h),
                              child: _buildSharePostCard(post),
                            );
                          }).toList(),
                    ),
          ),

          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  // 加载视图
  Widget _buildLoadingView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(height: 30.h),
          CircularProgressIndicator(color: Colors.white),
          SizedBox(height: 20.h),
          Text(
            'Loading...',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
            ),
          ),
          SizedBox(height: 200.h),
        ],
      ),
    );
  }

  // 未登录状态的视图
  Widget _buildNotLoggedInView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 图标
          Icon(Icons.account_circle_outlined, color: Colors.white, size: 80.sp),

          SizedBox(height: 24.h),

          // 标题
          Text(
            'Personal Center',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.sp,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              fontWeight: FontWeight.w400,
            ),
          ),

          SizedBox(height: 16.h),

          // 描述
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 40.w),
            child: Text(
              'You need to log in to view your personal information and releases',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white.withAlpha(180),
                fontSize: 16.sp,
                fontFamily: GoogleFonts.inter().fontFamily,
              ),
            ),
          ),

          SizedBox(height: 40.h),

          // 登录按钮
          GestureDetector(
            onTap: () {
              LoginDialog.show(context);
            },
            child: Container(
              width: 200.w,
              height: 50.h,
              decoration: BoxDecoration(
                color: MyColors.blue,
                borderRadius: BorderRadius.circular(25.r),
              ),
              alignment: Alignment.center,
              child: Text(
                'Log In',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserDataItem(String number, String label) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.baseline,
      textBaseline: TextBaseline.alphabetic,
      children: [
        Text(
          number,
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
            fontWeight: FontWeight.w400,
          ),
        ),
        SizedBox(width: 5.w),
        Text(
          label,
          style: TextStyle(
            color: Colors.white,
            fontSize: 14.sp,
            fontFamily: GoogleFonts.inter().fontFamily,
            fontWeight: FontWeight.w400,
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyView() {
    return Column(
      children: [
        SizedBox(height: 30.h),
        Image.asset(MyImages.empty, height: 120.h),
        SizedBox(height: 16.h),
        Text(
          'No posts yet',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontFamily: GoogleFonts.inter().fontFamily,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 8.h),
        Text(
          'Share your diving experiences',
          style: TextStyle(
            color: Colors.white.withAlpha(153),
            fontSize: 14.sp,
            fontFamily: GoogleFonts.inter().fontFamily,
            fontWeight: FontWeight.w400,
          ),
        ),
        // 占位
        SizedBox(height: 200.h),
      ],
    );
  }

  Widget _buildSharePostCard(dynamic post) {
    // 安全地获取用户信息
    final user = _authStore.currentUser;
    if (user == null) return Container(); // 安全保护

    // 获取用户名和头像
    final userName = user.name;
    final userAvatar =
        user.avatar.isNotEmpty ? user.avatar : MyImages.touxiang1;

    // 格式化日期
    final date = post.createdAt;
    final formattedDate =
        "${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}";

    // 获取收藏状态
    final isCollected = _collectStatus[post.id] ?? false;

    // 使用Card实现相同效果
    return GestureDetector(
      onTap: () {
        GoRouter.of(context).push('/share-detail/${post.id}');
      },
      child: Card(
        color: Colors.white.withAlpha(25),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        elevation: 0,
        margin: EdgeInsets.zero,
        child: Padding(
          padding: EdgeInsets.all(14.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部用户信息和收藏按钮行
              Row(
                children: [
                  // 头像
                  CircleAvatar(
                    radius: 22.r,
                    backgroundImage: AssetImage(userAvatar),
                  ),

                  SizedBox(width: 8.w),

                  // 用户名
                  Text(
                    userName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                  ),

                  const Spacer(),

                  // 收藏图标 - 更新为可交互并显示正确的收藏状态
                  GestureDetector(
                    onTap: () => _toggleCollect(post.id),
                    child: Container(
                      padding: EdgeInsets.all(8.r),
                      decoration: BoxDecoration(
                        color: MyColors.iconDark,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        isCollected
                            ? MyIcons.iconCollectFill
                            : MyIcons.iconCollect,
                        color: isCollected ? Colors.red : Colors.white,
                        size: 24.sp,
                      ),
                    ),
                  ),
                ],
              ),

              SizedBox(height: 12.h),

              // 描述文本
              Text(
                post.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  height: 1.5,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),

              SizedBox(height: 12.h),

              // 图片展示区域
              SizedBox(
                height: 113.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children:
                      post.imageUrls.isNotEmpty
                          ? post.imageUrls.take(3).map<Widget>((image) {
                            return ClipRRect(
                              borderRadius: BorderRadius.circular(12.r),
                              child: SizedBox(
                                width: 113.w,
                                height: 113.h,
                                child: Image.asset(image, fit: BoxFit.cover),
                              ),
                            );
                          }).toList()
                          : [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(12.r),
                              child: Container(
                                width: 113.w,
                                height: 113.h,
                                color: Colors.grey[800],
                                child: Icon(Icons.image, color: Colors.white54),
                              ),
                            ),
                          ],
                ),
              ),

              SizedBox(height: 12.h),

              // 底部查看信息和删除按钮
              Row(
                children: [
                  // 已浏览头像 - 使用viewerIds创建头像列表
                  SizedBox(
                    width: 120.w,
                    height: 37.h,
                    child:
                        post.viewerIds.isEmpty
                            ? Center(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10.w,
                                  vertical: 5.h,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.2),
                                  borderRadius: BorderRadius.circular(15.r),
                                ),
                                child: Text(
                                  'No viewers yet',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 10.sp,
                                    fontFamily: GoogleFonts.inter().fontFamily,
                                  ),
                                ),
                              ),
                            )
                            : Stack(
                              children: List.generate(
                                post.viewerIds.length > 4
                                    ? 4
                                    : post.viewerIds.length,
                                (index) {
                                  // 根据viewerId获取用户信息
                                  final viewerId = post.viewerIds[index];
                                  final UserService userService =
                                      getIt<UserService>();
                                  final UserModel? viewer = userService
                                      .getUserById(viewerId);
                                  final String avatarPath =
                                      viewer?.avatar ?? MyImages.touxiang1;

                                  return Positioned(
                                    left: index * 25.w,
                                    child: Container(
                                      decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        border: Border.all(
                                          color: MyColors.blue,
                                          width: 1.w,
                                        ),
                                      ),
                                      child: CircleAvatar(
                                        radius: 18.r,
                                        backgroundImage: AssetImage(avatarPath),
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                  ),

                  SizedBox(width: 4.w),

                  // Already viewed 文字
                  Text(
                    post.viewerIds.isEmpty ? '' : 'Already viewed',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 11.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                      height: 1.36,
                    ),
                  ),

                  const Spacer(),

                  // 删除按钮
                  GestureDetector(
                    onTap: () async {
                      // 显示确认对话框
                      showDialog(
                        context: context,
                        builder:
                            (context) => AlertDialog(
                              backgroundColor: MyColors.cardDark,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(16.r),
                              ),
                              title: Text(
                                'Delete Post',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              content: Text(
                                'Are you sure you want to delete this post? This action cannot be undone.',
                                style: TextStyle(
                                  color: Colors.white.withOpacity(0.9),
                                  fontSize: 16.sp,
                                ),
                              ),
                              actions: [
                                TextButton(
                                  onPressed: () => Navigator.pop(context),
                                  child: Text(
                                    'Cancel',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 16.sp,
                                    ),
                                  ),
                                ),
                                TextButton(
                                  onPressed: () async {
                                    // 关闭对话框
                                    Navigator.pop(context);

                                    // 显示加载提示
                                    final loadingToast = MyToast.showLoading(
                                      context,
                                      'Deleting post...',
                                    );

                                    try {
                                      // 删除分享
                                      await _shareStore.deleteShare(post.id);

                                      // 关闭加载提示
                                      MyToast.dismiss(loadingToast);

                                      // 显示成功提示
                                      MyToast.showSuccess(
                                        context,
                                        'Post deleted successfully',
                                      );

                                      // 重新加载数据
                                      await _shareStore.loadShares();
                                    } catch (e) {
                                      // 关闭加载提示
                                      MyToast.dismiss(loadingToast);

                                      if (mounted) {
                                        MyToast.showError(
                                          context,
                                          "Failed to delete: $e",
                                        );
                                      }
                                    }
                                  },
                                  style: TextButton.styleFrom(
                                    backgroundColor: Colors.red.withOpacity(
                                      0.8,
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8.r),
                                    ),
                                  ),
                                  child: Text(
                                    'Delete',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                      );
                    },
                    child: DecoratedBox(
                      decoration: BoxDecoration(
                        color: MyColors.iconDark,
                        shape: BoxShape.circle,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(8.r),
                        child: Icon(
                          Icons.delete,
                          color: Colors.white,
                          size: 20.sp,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
